package com.yygo.util;

import com.yygo.configentity.feedback.Role;
import com.yygo.configentity.feedback.RoleFeedback;
import com.yygo.configentity.feedback.RoleFeedbacks;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * Created by huanli on 2015/11/12.
 */
public class RoleFeedbackConfigUtil {
    private static Log log = LogFactory.getLog(RoleFeedbackConfigUtil.class);
    public RoleFeedbacks read(){
        RoleFeedbacks roleFeedbacks = new RoleFeedbacks();
        SAXReader saxReader= new SAXReader();
        Document document = null;
        try{
            URL xmlPath = this.getClass().getClassLoader().getResource("RoleFeedback.xml");
            document = saxReader.read(xmlPath);
            Element root = document.getRootElement();
            List<Element> childList = root.elements();
            List<Role> roles = new ArrayList<>();
            for (Element childNode:childList) {
                Role role = new Role();
                String name = childNode.valueOf("@name" );
                role.setName(name);
                List<RoleFeedback> roleFeedbackList = new ArrayList<>();
                for(Object properties: childNode.elements("Feedback")) {
                    RoleFeedback roleFeedback = new RoleFeedback();
                    String phase = ((Node) properties).valueOf("@phase");
                    String toRole = ((Node) properties).valueOf("@toRole");
                    boolean requireRespond = ((Node) properties).valueOf("@requireRespond").equals("true")? true:false;
                    roleFeedback.setPhase(phase);
                    roleFeedback.setRequireRespond(requireRespond);
                    roleFeedback.setToRole(toRole);
                    roleFeedbackList.add(roleFeedback);
                }
                role.setFeedbacks(roleFeedbackList);
                roles.add(role);
            }
            roleFeedbacks.setRoles(roles);
        }
        catch(Exception e){
            log.trace(e.getMessage());
        }
        return roleFeedbacks;
    }
}
